package com.john.blog.controller.back;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.john.blog.common.constant.KeyConst;
import com.john.blog.common.utils.DetectUtils;
import com.john.blog.common.utils.GraphicHelper;
import com.john.blog.common.utils.KeyUtils;
import com.john.blog.common.vo.CommonResult;
import com.john.blog.controller.back.support.BackBlogControllerSupport;
import com.john.blog.model.po.User;
import com.john.blog.service.UserService;

import tk.mybatis.mapper.entity.Example;

/**
 * 通用方法接口
 * 
 * @author JiangGengchao
 * @date 2018年2月25日
 */
@RestController
public class BackCommonController extends BackBlogControllerSupport {

    @Autowired
    private UserService userService;

    @RequestMapping("/validateCode")
    public void validateCode(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
        response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);

        try {
            request.getSession().removeAttribute(KeyConst.VALIDATECODE_SESSION_KEY);
            String randomString = GraphicHelper.create(80, 40, "JPEG", response.getOutputStream());
            request.getSession().setAttribute(KeyConst.VALIDATECODE_SESSION_KEY, randomString);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 登录
     */
    @RequestMapping("/doLogin")
    public CommonResult doLogin(HttpServletRequest request, @RequestParam(value = "valicode") String code, @RequestParam(value = "username") String username,
            @RequestParam(value = "password") String password) {
        if (!checkValidateCode(request, code)) {
            return CommonResult.build(CommonResult.Code.CODE_ERROR, "验证码错误");
        }
        if (username == null || username.trim().length() == 0) {
            return CommonResult.build(CommonResult.Code.CODE_ERROR, "用户名不能为空");
        }
        if (password == null || password.trim().length() == 0) {
            return CommonResult.build(CommonResult.Code.CODE_ERROR, "密码不能为空");
        }
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("username", username);
        List<User> users = userService.selectByExample(example);
        if (DetectUtils.isEmpty(users) && users.size() != 1) {
            return CommonResult.build(CommonResult.Code.CODE_ERROR, username + "用户不存在或不唯一");
        }
        // 校验密码
        User user = users.get(0);
        password = KeyUtils.signByMD5(password);
        if (password.equals(user.getPassword())) {
            request.getSession().setAttribute(KeyConst.USER_SESSION_KEY, user);
            return CommonResult.success();
        } else {
            return CommonResult.build(CommonResult.Code.CODE_ERROR, username + "用户名或密码错误");
        }
    }

    /**
     * 检查登录
     */
    @RequestMapping("/checkLogin")
    public CommonResult checkLogin(HttpServletRequest request) {
        if (null != request.getSession().getAttribute(KeyConst.USER_SESSION_KEY)) {
            return CommonResult.success();
        } else {
            return CommonResult.error();
        }
    }

    /**
     * 退出登录
     */
    @RequestMapping("/logout")
    public void logout(HttpServletRequest request) {
        request.getSession().invalidate();
    }

    /**
     * 修改密码
     */
    @RequestMapping("/passwd")
    public CommonResult password(HttpServletRequest request, @RequestParam(value = "pass1") String pass1, @RequestParam(value = "pass2") String pass2) {
        if (DetectUtils.isEmpty(pass1)) {
            return CommonResult.build(CommonResult.Code.CODE_ERROR, "密码不能为空");
        }
        if (DetectUtils.isEmpty(pass2)) {
            return CommonResult.build(CommonResult.Code.CODE_ERROR, "密码不能为空");
        }
        if (!pass1.equals(pass2)) {
            return CommonResult.build(CommonResult.Code.CODE_ERROR, "两次密码不一致");
        }
        User user = (User) request.getSession().getAttribute(KeyConst.USER_SESSION_KEY);
        if (user == null) {
            return CommonResult.build(CommonResult.Code.CODE_ERROR, "用户不存在");
        }
        String password = KeyUtils.signByMD5(pass1);
        user.setPassword(password);
        userService.updateByPrimaryKeySelective(user);
        if (userService.updateByPrimaryKeySelective(user) != null) {
            return CommonResult.build(CommonResult.Code.SUCCESS, "修改成功");
        } else {
            return CommonResult.build(CommonResult.Code.FAILURE, "修改失败");
        }
    }

    /**
     * 校验验证码
     * 
     * @param request
     * @param code
     * @return
     */
    private boolean checkValidateCode(HttpServletRequest request, String code) {
        String validateCode = (String) request.getSession().getAttribute(KeyConst.VALIDATECODE_SESSION_KEY);
        if (null != validateCode && validateCode.equals(code)) {
            return true;
        } else {
            return false;
        }
    }
}
